package algorithm.leetcode.I1to100;

import java.util.ArrayList;
import java.util.List;

public class Q93 {

    public static List<String> restoreIpAddresses(String s) {
        if (s.length() < 4 || s.length() > 12) {
            return new ArrayList<>();
        } else {
            int[] firstDot = {1, 2, 3};
            int[] secondDot = {2, 3, 4, 5, 6};
            int[] thirdDot = {3, 4, 5, 6, 7, 8, 9};

            List<String> result = new ArrayList<>();

            for (int i : firstDot) {
                for (int j : secondDot) {
                    for (int k : thirdDot) {
                        if (i < j && j < k) {
                            try {
                                String ipStr = s.substring(0, i) + "." + s.substring(i, j) + "." + s.substring(j, k) + "." + s.substring(k, s.length());
                                if (isLegal(ipStr)) {
                                    result.add(ipStr);
                                }
                            } catch (StringIndexOutOfBoundsException e) {
                                break;
                            }

                        }
                    }
                }
            }

            return result;
        }


    }

    public static boolean isLegal(String s) {
        String[] ipAry = s.split("\\.");

        int count = 0;

        for (String s1 : ipAry) {
            if (0 <= Integer.parseInt(s1) && Integer.parseInt(s1) <= 255) {
                if (s1.length() == 1 || (!s1.startsWith("0") && s1.length() > 1)) {
                    count += 1;
                }
            }
        }

        return count == 4;
    }

    public static void main(String[] args) {
        String ss = "0279245587303";
//        String ss = "010010";
        System.out.println(restoreIpAddresses(ss));
    }
}
